package com.example.ktdemo.poptopbar;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * Author: lzt
 * Date: 2022/10/20 10:40
 */
public class TopBarPopSlideLayout extends RelativeLayout {
    //点击时候的x，y轴
    private float mTouchX, mTouchY;
    //是否向下滑动
    private boolean mDownSwipe = false;

    //监听
    private OnSwipeEventListener mSwipeEventListener;

    public TopBarPopSlideLayout(@NonNull Context context) {
        super(context);
    }

    public TopBarPopSlideLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TopBarPopSlideLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int actionEvent = event.getAction();
        switch (actionEvent) {
            case MotionEvent.ACTION_DOWN:
                this.mTouchX = event.getX();
                this.mTouchY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                float moveY = event.getY();
                if (moveY > mTouchY) {
                    mDownSwipe = true;
                } else {
                    mDownSwipe = false;
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                //取消
                break;
            case MotionEvent.ACTION_UP:
                //回调
                notifyVerticalEvent(mDownSwipe);
                break;

        }
        return true;
    }


    //接口回调--------------------------------------------------------------------------

    /**
     * 通知回调
     */
    private void notifyVerticalEvent(boolean downSwipe) {
        if (mSwipeEventListener != null) {
            if (downSwipe) {
                mSwipeEventListener.down();
            } else {
                mSwipeEventListener.up();
            }
        }
    }


    public interface OnSwipeEventListener {
        void down();

        void up();
    }

    public void setOnSwipeEventListener(OnSwipeEventListener listener) {
        this.mSwipeEventListener = listener;
    }

    public void removeOnSwipeEventListener() {
        this.mSwipeEventListener = null;
    }
}
